from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.core.files import File
from django.core.servers.basehttp import FileWrapper

from Profile.models import UserConf
from conference.forms import PaymentForm
from conference.models import Conference

import datetime
import Image, ImageDraw, ImageFont

# generate a nametag; just spits out a PNG
def nametag(request, conference):
	# load the font 
	fontpath = "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf"
	dejavu = ImageFont.truetype(fontpath, 18)

	size = (400, 250)
	im = Image.new("RGB", size, color="#dcdcdc")
	draw = ImageDraw.Draw(im)
	
	TEXT_COLOR = ("black")
	conf_pos = (120, 15)
	text_pos = (120,100)
	ctext = "Conference: {0}".format(conference)
	text = "HELLO I AM " + request.user.username
	box = (400, 250, 5, 5)
	draw.text(text_pos, text, font=dejavu, fill=TEXT_COLOR)
	draw.text(conf_pos, ctext, font=dejavu, fill=TEXT_COLOR)

	del draw

	response = HttpResponse(mimetype="image/png")
	im.save(response, 'PNG')
	return response

# view for payment on a conference
def payment(request, conference):
	errors = False
	if request.method == 'POST':
		f = PaymentForm(request.POST)
		# validate the form
		if f.is_valid():
			# if it's valid, set the paid flag in the user's conference
			conf = Conference.objects.get(name=conference)
			uprof = request.user.get_profile()
			# we need to find the conference
			for i in uprof.conf.all():
				if i.conf == conference:
					# if we found it, clear all it's m2m links and instantiate a new one
					for i in UserConf.objects.filter(conf=conference).all():
						request.user.profile.conf.remove(i)
					# include the new userconf with the paid flag set
					uconf = UserConf.objects.create(conf=conf.name,
									registered=True, paid=True)
					uprof.conf.add(uconf)
			# redirect to the conference page for further stuff	
			return render_to_response('payment_complete.html', {'loggedin': True,'user':request.user},
						context_instance=RequestContext(request))
	else:
		f = PaymentForm()

	return render_to_response('payment.html', {'loggedin': request.user.is_authenticated(),
												'form': f, 'errors': errors },
						context_instance=RequestContext(request))

# show the moderater options 
def moderate(request, conference):
	conf = Conference.objects.get(name=conference)
	# if they're changing the room...
	if request.method == 'POST':
		room = request.POST.get('room', '')
		conf.room = room
		conf.save()
	return render_to_response('moderate.html', {'loggedin': request.user.is_authenticated(),
					'conference':conf},
						context_instance=RequestContext(request))

# view users checked in
def moderate_checked_in(request, conference):
	users_in = {}
	users = User.objects.all()
	for c in users:
		if c.profile.conf.filter(conf=conference):
			conf = c.profile.conf.get(conf=conference)
			if conf.checked_in:
				users_in[c] = conf.checked_in_time
	return render_to_response('moderate_registered.html', {'loggedin': True, 'checked_in': True,
					'conference':conference, 'users':users_in},
						context_instance=RequestContext(request))

# view users checked out
def moderate_checked_out(request, conference):
	users_out = {}
	users = User.objects.all()
	for c in users:
		if c.profile.conf.filter(conf=conference):
			conf = c.profile.conf.get(conf=conference)
			if not conf.checked_in:
				users_out[c] = conf.checked_out_time
	return render_to_response('moderate_registered.html', {'loggedin': True, 'checked_out': True,
					'conference':conference, 'users':users_out},
						context_instance=RequestContext(request))

# view admins
def moderate_admins(request, conference):
	# get the conference object, then all of its admins
	conf = Conference.objects.get(name=conference)
	admins = conf.admins.all()
	return render_to_response('moderate_registered.html', {'loggedin': True, 'admins': True,
							  'users': admins, 'conference':conference},
						context_instance=RequestContext(request))

# view registered users
def moderate_registered_users(request, conference):
	users_in_conf = []
	users = User.objects.all()
	# get a list of all users attending this conference
	for c in users:
		if c.profile.conf.filter(conf=conference):
			users_in_conf.append(c.username)
	return render_to_response('moderate_registered.html', {'loggedin': request.user.is_authenticated(),
							  'registered_users': True, 'users':users_in_conf, 'conference':conference },
						context_instance=RequestContext(request))

# view breakout groups
def moderate_breakout_groups(request, conference):
	users_in_conf = []
	users = User.objects.all()
	# get a list of all users attending this conference
	for c in users:
		if c.profile.conf.filter(conf=conference):
			users_in_conf.append(c.username)

	breakout_group = []
	groups = users_in_conf.__len__() / 3
	if users_in_conf.__len__() % 3 != 0:
		groups += 1 
	counter = 0
	for i in range(groups):
		temp = []
		temp.append(users_in_conf[counter])
		counter += 1
		if counter < users_in_conf.__len__():
			temp.append(users_in_conf[counter])
			counter += 1
		if counter < users_in_conf.__len__():
			temp.append(users_in_conf[counter])
			counter += 1
		breakout_group.append(temp)

	return render_to_response('breakout_groups.html', {'loggedin': request.user.is_authenticated(),
							  'registered_users': True, 'users':users_in_conf, 'conference':conference, 'breakout':breakout_group },
						context_instance=RequestContext(request))

# this is the view for setting up transportation and stuff
def transportation(request):
	return render_to_response('transport.html', {'loggedin': request.user.is_authenticated()},
						context_instance=RequestContext(request))

# check in to a conference
def checkin(request, conference):
	conf = Conference.objects.get(name=conference)
	uprof = request.user.get_profile()
	# find the conference in their account
	for i in uprof.conf.all():
		if i.conf == conference:
			# sanity check
			if not i.checked_in:
				# generate new
				uconf = UserConf.objects.create(conf=conf.name, 
							registered=True, paid=i.paid, checked_in=True, 
							checked_in_time=datetime.datetime.now())
				# remove old m2m links..
				for i in UserConf.objects.filter(conf=conference).all():
					request.user.profile.conf.remove(i)
				# add new one in
				uprof.conf.add(uconf)
			return HttpResponseRedirect("/conference/" + conference)
	return HttpResponse("checkin for %s for user %s"%(conference, request.user.username))

# check out of a conference
def checkout(request, conference):
	conf = Conference.objects.get(name=conference)
	uprof = request.user.get_profile()
	# find the conference in their account
	for i in uprof.conf.all():
		if i.conf == conference:
			# sanity check
			if  i.checked_in:
				# generate new
				uconf = UserConf.objects.create(conf=conf.name, 
							registered=True, paid=i.paid, checked_in=False, 
							checked_out_time=datetime.datetime.now())
				# remove old m2m links..
				for i in UserConf.objects.filter(conf=conference).all():
					request.user.profile.conf.remove(i)
				# add new one in
				uprof.conf.add(uconf)
			return HttpResponseRedirect("/conference/" + conference)
	return HttpResponse("checkout for %s for user %s"%(conference, request.user.username))

# returns the conferences itinerary
def get_itinerary(request, conference):
	conf = Conference.objects.get(name=conference)
	f = open(conf.itinerary.name)
	myfile = File(f) 
	response = HttpResponse(FileWrapper(myfile), content_type='application/zip')
	response['Content-Disposition'] = 'attachment; filename=myfile.zip'
	return HttpResponse(response)
